package com.scnlf.scnlf.portal.core.business.event.manager.loan.impl;

import com.scnlf.scnlf.portal.core.business.common.enums.FlowTypeEnum;
import com.scnlf.scnlf.portal.core.business.common.enums.OptionEventTypeEnum;
import com.scnlf.scnlf.portal.core.business.event.manager.loan.ILoanEventService;
import com.scnlf.scnlf.portal.core.business.event.param.OptionEvent;
import com.scnlf.scnlf.portal.core.business.event.param.OptionEventParam;
import com.scnlf.scnlf.portal.core.business.event.param.loan.LoanOpenOptionEventParam;
import java.util.Objects;
import java.util.concurrent.ConcurrentLinkedQueue;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LoanWorkThread extends Thread {

  private ConcurrentLinkedQueue<OptionEvent> queue = new ConcurrentLinkedQueue<>();

  private ILoanEventService loanEventService;

  private Long waitBeginTime;

  public LoanWorkThread(ILoanEventService loanEventService){
    this.loanEventService = loanEventService;
  }

  public void push(OptionEvent optionEvent){
    if(Objects.nonNull(optionEvent)){
      queue.add(optionEvent);
    }
  }

  @Override
  public void run() {
    while(true){
      try{
        OptionEvent optionEvent = queue.poll();
        if(Objects.isNull(optionEvent)){
          if(null == waitBeginTime){
//          log.info("work thread task is first empty");
            waitBeginTime = System.currentTimeMillis();
          } else {
//          log.info("work thread task is empty, time = {}", System.currentTimeMillis() - waitBeginTime);
          }
          Thread.sleep(200);
          continue;
        }
        waitBeginTime = null;
        doLoanTask(optionEvent);
      } catch (Exception e){
        log.error("work task exception", e);
      }
    }
  }

  /**
   * 执行任务
   * @param optionEvent
   */
  private void doLoanTask(OptionEvent optionEvent){
    OptionEventTypeEnum eventType = optionEvent.getEventType();
    OptionEventParam param = optionEvent.getParam();
    if(OptionEventTypeEnum.LOAN_OPEN == eventType){
      LoanOpenOptionEventParam loanOpenParam = (LoanOpenOptionEventParam) param;
      FlowTypeEnum examineStatus = loanEventService.getExamineStatus(loanOpenParam.getEventId());
      if(FlowTypeEnum.CONFIRMED == examineStatus){
        loanEventService.loanConfirmWithFail(loanOpenParam.getEventId());
      }
    }
  }

}
